<template>
    <div class="app-container">
        <div class="filter-container">

          <el-button v-has="'contractRightsTable_add'" class="filter-item"  @click="handleCreate" type="primary" icon="el-icon-plus" >新增授权</el-button>
          <el-button v-has="'contractRightsTable_mutilDisable'" class="filter-item" @click="handleBatchInvalid" type="primary" icon="el-icon-circle-close-outline" >{{$t('table.batchInvalid')}}</el-button>
          <el-button v-has="'contractRightsTable_export'" class="filter-item" @click="handleExcelExport" type="primary" icon="el-icon-download" >{{$t('table.excelExport')}}</el-button>
          <el-button v-has="'contractRightsTable_import'" class="filter-item" style="margin-right: 10px;" type="primary" icon="el-icon-files-excel" @click="downloadTem">{{$t('table.downloadTem')}}</el-button>
          <el-upload
            class="upload-demo"
            :action="importUrl"
            :on-success="importSuccess"
            :show-file-list="false"
            :beforeUpload="beforeAvatarUpload"
            :headers="uploadHeaders"
          >
            <el-button v-has="'contractRightsTable_import'" class="filter-item" type="primary" icon="el-icon-upload" >{{$t('table.batchImport')}}</el-button>
          </el-upload>

          <br/>

              <el-input style="width: 300px;" class="filter-item" placeholder="作品名称/出版社/合同编号/版权号/授权号" v-model="listQuery.compoundSearch">
              </el-input>
          <br/>

          <div class="search_box">
            <span class="search_notice">到期状态:</span>
            <div class="search_field">
              <el-radio-group v-model="listQuery.expireStatus" @change="handleFilter">
                <el-radio v-for="item in $expireOptions" :label="item.key" :key="item.key">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="search_box">
            <span class="search_notice">结算形式:</span>
            <div class="search_field">
              <el-radio-group v-model="listQuery.balanceType" @change="handleFilter">
                <el-radio v-for="item in $balanceTypeOptions" :label="item.key" :key="item.key">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="search_box">
            <span class="search_notice">是否独家授权:</span>
            <div class="search_field">
              <el-radio-group v-model="listQuery.soleFlag" @change="handleFilter">
                <el-radio v-for="item in $ynOptions" :label="item.key" :key="item.key">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="search_box">
            <span class="search_notice">有无转授权:</span>
            <div class="search_field">
              <el-radio-group v-model="listQuery.subRightsFlag" @change="handleFilter">
                <el-radio v-for="item in $tfOptions" :label="item.key" :key="item.key">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="search_box">
            <span class="search_notice">授权状态:</span>
            <div class="search_field">
              <el-radio-group v-model="listQuery.statis" @change="handleFilter">
                <el-radio v-for="item in $statusOptions" :label="item.key" :key="item.key">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="search_box">
            <span class="search_notice">授权范围:</span>
            <div class="search_field checkbox">
              <el-checkbox-group v-model="contractRightsRangeArr" @change="handleFilter">
                <el-checkbox v-for="range in $copyrightsRangeOptions" :label="range.key" :key="range.key">{{range.label}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>

          <br/>

          <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>

          <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>



          <br/>



        </div>

        <el-table :key='tableKey' ref="table" :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
                  style="width: 100%"
                  @selection-change="selectionChange">
            <el-table-column disabled :selectable='checkboxInit' type="selection" width="35" ></el-table-column>
            <el-table-column align="center" :label="$t('table.showId')" width="65">
              <template slot-scope="scope">
                <span>{{scope.row.showId}}</span>
              </template>
            </el-table-column>

          <el-table-column align="center" label="授权号">
            <template slot-scope="scope">
              <span>{{scope.row.contractRightsNo}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="版权号">
            <template slot-scope="scope">
              <span>{{scope.row.copyrightsNo}}</span>
            </template>
          </el-table-column>


          <el-table-column align="center" label="出版社">
            <template slot-scope="scope">
              <span>{{scope.row.publishingName}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="作品名称">
            <template slot-scope="scope">
              <span>{{scope.row.worksName}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="合同编号">
            <template slot-scope="scope">
              <span>{{scope.row.contractNo}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="到期状态">
            <template slot-scope="scope">
              <span>{{scope.row.expireStatus}}</span>
            </template>
          </el-table-column>


          <el-table-column align="center" label="授权状态">
            <template slot-scope="scope">
              <span>{{scope.row.statis | $statusFilter}}</span>
            </template>
          </el-table-column>


          <el-table-column align="center" label="开始时间">
            <template slot-scope="scope">
              <span>{{scope.row.beginDate | $dateConvert}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="终止时间">
            <template slot-scope="scope">
              <span>{{scope.row.endDate | $dateConvert}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="合作形式">
            <template slot-scope="scope">
              <span>{{scope.row.balanceType | $balanceTypeFilter}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="独家授权">
            <template slot-scope="scope">
              <span>{{scope.row.soleFlag | $ynFilter}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="转授权">
            <template slot-scope="scope">
              <span>{{scope.row.subRightsFlag | $tfFilter}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="原始版权">
            <template slot-scope="scope">
              <span>{{scope.row.originalCopyrightsFlag | $provideFilter}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作人">
            <template slot-scope="scope">
              <span>{{scope.row.modifier}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="修改时间">
            <template slot-scope="scope">
              <span>{{scope.row.modifyTime | $dateConvert("YYYY-MM-DD HH:mm:ss")}}</span>
            </template>
          </el-table-column>


            <el-table-column align="center" :label="$t('table.actions')" width="230" class-name="small-padding fixed-width">


                <template slot-scope="scope">
                  <el-button v-show="scope.row.statis=='VALID'" v-has="'contractRightsTable_edit'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
                  <el-button v-has="'contractRightsTable_info'" type="info" size="mini" @click="handleContractRightsInfo(scope.row)">{{$t('table.info')}}</el-button>
                  <el-button v-has="'contractRightsTable_info'" type="info" size="mini" @click="handleCopyrigthsInfo(scope.row)">版权详情</el-button>
                  <el-button v-has="'supplyContractTable_info'" type="info" size="mini" @click="handleSupplyContractInfo(scope.row)">合同详情</el-button>
                  <el-button v-show="scope.row.statis=='VALID'" v-has="'contractRightsTable_disable'" size="mini" type="danger" @click="handleInvalid(scope.row,'invalid')">{{$t('table.invalid')}}</el-button>
                </template>



            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

    </div>
</template>

<script>
    import { fetchList, invalidContractRights, batchInvalid } from '@/api/contractRights/contractRights'
    import waves from '@/directive/waves' // 水波纹指令
    import { parseTime } from '@/utils'
    import store from '@/store'

    export default {
      name: 'contractRights',
      directives: {
        waves
      },
      components: { waves },
      data() {
        return {
          tableKey: 0,
          list: null,
          total: null,
          listLoading: true,
          page: {
            page: 1,
            limit: 50,
            sort: ''
          },
          listQuery: {
            compoundSearch: undefined,
            expireStatus: undefined,
            clearMethod: undefined,
            statis: undefined,
            'page.limit': 50,
            'page.sort': 'SHOW_ID',
            'page.order': 'DESC'
          },
          contractRightsRangeArr: [],
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
            update: '修改',
            create: '新增',
            info: '详情'
          },
          dialogPvVisible: false,
          pvData: [],
          rules: {
          },
          downloadLoading: false,
          // 批量失效的id
          selectIds: '',
          importUrl: process.env.BASE_API + '/contractRights/importExcel.do'
        }
      },
      filters: {

      },
      computed: {
        uploadHeaders() {
          if (store.getters.token) {
            return {
              'Authorization': store.getters.token
            }
          }
        }
      },
      created() {
        this.getList()
        this.getExpireOption()
  },
      methods: {
        getList() {
          this.listLoading = true
          fetchList(this.listQuery).then(response => {
            if (response.success) {
              this.list = response.content.list
              this.total = response.content.total
              this.listLoading = false
              this.$refs.table.clearSelection()
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        },
        getExpireOption() {
          this.listLoading = true
          fetchList(this.listQuery).then(response => {
            if (response.success) {
              this.list = response.content.list
              this.total = response.content.total
              this.listLoading = false
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        },
        // 搜索按钮
        handleFilter() {
          this.listQuery.page = 1
          // 修改范围
          const contractRightsRangeArr = this.contractRightsRangeArr
          let rightsRange = ''
          for (var i = 0; i < contractRightsRangeArr.length; i++) {
            var item = contractRightsRangeArr[i]
            rightsRange += item
            if (i !== contractRightsRangeArr.length - 1) {
              rightsRange += ','
            }
          }
          this.listQuery.copyrightsRange = rightsRange
          this.getList()
        },
        // 跳转页数
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.getList()
        },
        // 详情
        handleInfo(row, status) {
          const id = row.id
          this.$router.push({ name: 'contractRightsInfo', query: { id: id, opt: 'info' }})
        },
        // 合同详情
        handleContractInfo(row, status) {
          const contractNo = row.contractNo
          this.$router.push({ name: 'supplyContractInfo', query: { contractNo: contractNo, opt: 'info' }})
        },

        // 打开跳转新增页面
        handleCreate() {
          this.$router.push({ name: 'contractRightsAdd' })
        },

        // 更新页面
        handleUpdate(row) {
          const id = row.id
          this.$router.push({ name: 'contractRightsEdit', query: { id: id }})
        },

        // 删除操作
        // handleDelete(row) {
        //   this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).then((response) => {
        //     // 调用删除接口
        //     var p = { id: row.id }
        //     deleteCopyrights(p).then(response => {
        //       if (response.success) {
        //         this.getList()
        //         this.$message({
        //           type: 'success',
        //           message: '删除成功!'
        //         })
        //       } else {
        //         this.$message({
        //           type: 'fail',
        //           message: response.message
        //         })
        //       }
        //     })
        //   }).catch(() => {
        //     this.$message({
        //       type: 'info',
        //       message: '已取消删除'
        //     })
        //   })
        // },
        // 失效操作
        handleInvalid(row) {
          this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((response) => {
            // 调用失效接口
            var p = { id: row.id }
            invalidContractRights(p).then(response => {
              if (response.success) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              } else {
                this.$message({
                  type: 'fail',
                  message: response.message
                })
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        },
        // 初始化页面,批量失效,已失效不允许勾选
        checkboxInit(item) {
          var status = item.statis
          if (status === 'VALID') {
            return 1
          } else {
            return 0
          }
        },
        handleBatchInvalid() {
          // 判断是否选择
          if (!this.selectIds) {
            this.$message({
              type: 'fail',
              message: '请先选择数据，再进行失效操作!'
            })
            return
          }
          // TODO 批量失效
          this.$confirm('失效后，所选数据不可操作，确认失效?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((response) => {
            // 调用批量失效接口
            var params = { 'invalidIds': this.selectIds }
            batchInvalid(params).then(response => {
              if (response.success) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              } else {
                this.$message({
                  type: 'fail',
                  message: response.message
                })
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        },
        handleBatchImport() {
          // TODO 批量导入
        },
        handleExcelExport() {
          this.$alert('导出需要一定时间,请耐心等待', '导出提示', {
            confirmButtonText: '导出',
            callback: action => {
              if (action === 'cancel') {
                return
              }
              this.$message({
                type: 'info',
                message: '正在导出...'
              })
              var params = ''
              for (const field in this.listQuery) {
                const val = this.listQuery[field]
                if (typeof val !== 'undefined' && val !== '') {
                  params += field + '=' + val + '&'
                }
              }
              if (!params.endsWith('&')) {
              // 加上token
                params += '&'
              }
              params += 'token=' + store.getters.token
              window.open(process.env.BASE_API + '/contractRights/exportExcel.do?' + params)
            }
          })
        },
        selectionChange(selects) {
          this.selectIds = ''
          for (var select of selects) {
            this.selectIds += select.id
            this.selectIds += ','
          }
          this.selectIds = this.selectIds.substring(0, this.selectIds.length - 1)
        },
        // 版权详情
        handleCopyrigthsInfo(row) {
          const copyrightsNo = row.copyrightsNo
          this.$router.push({ name: 'copyrightsInfo', query: { copyrightsNo: copyrightsNo, opt: 'info' }})
        },
        // 授权详情
        handleContractRightsInfo(row) {
          const id = row.id
          this.$router.push({ name: 'contractRightsInfo', query: { id: id, opt: 'info' }})
        },
        // 合同信息
        handleSupplyContractInfo(row) {
          const contractNo = row.contractNo
          this.$router.push({ name: 'supplyContractInfo', query: { contractNo: contractNo, opt: 'info' }})
        },
        importSuccess(response) {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '导入成功'
            })
            this.getList()
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        },
        // 上传前对文件的类型的判断
        beforeAvatarUpload(file) {
          const extension = file.name.split('.')[1] === 'xls'
          const extension2 = file.name.split('.')[1] === 'xlsx'
          if (!extension && !extension2) {
            this.$message({
              type: 'fail',
              message: '只能上传excel文件'
            })
          }
          return extension || extension2
        },
        downloadTem() {
          window.open(process.env.BASE_URL + '/授权导入模板.xlsx')
          // window.open("http://47.96.144.33:8888/download?filename=%2Fwww%2Fwwwroot%2F%E6%8E%88%E6%9D%83%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx");
        },
        restQuery() {
          this.listQuery.compoundSearch = ''
          this.listQuery.expireStatus = ''
          this.listQuery.balanceType = ''
          this.listQuery.soleFlag = ''
          this.listQuery.subRightsFlag = ''
          this.listQuery.statis = ''
          this.contractRightsRangeArr = []
          this.getList()
        },
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          }))
        }
      }
    }
</script>


<style scoped>
  .search_box {
    width: 1000px;
    margin-top: 10px;
  }

  .search_box span{
    display: inline-block;
    float: left;
    font-size: 15px;
  }

  .search_notice {
    width: 120px;
  }

  .search_field {
    margin-left: 10px;
  }

  .search_field.checkbox span {
    margin-top: 2px;
  }

  .el-radio {
    width: 130px;
  }

  .el-checkbox {
    width: 130px;
  }

  .el-radio+.el-radio {
    margin-left: 0px;
  }

  .el-checkbox+.el-checkbox {
    margin-left: 0px;
  }
</style>
